package com.mryan.ps_auth.controller;

import com.mryan.ps_auth.service.ValidateCodeService;
import com.mryan.ps_common.entity.PSResponse;
import com.mryan.ps_common.exception.PSAuthException;
import com.mryan.ps_common.exception.ValidateCodeException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.security.Principal;

/**
 * @BelongsProject: ps_cloud
 * @BelongsPackage: com.mryan.ps_auth.controller
 * @Author: Yan
 * @CreateTime: 2021-04-23 21:12
 * @Description:
 */
@RestController
public class SecurityController {

	@Autowired
	private ConsumerTokenServices consumerTokenServices;

	@Autowired
	private ValidateCodeService validateCodeService;

	@GetMapping("captcha")
	public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException, ValidateCodeException, FontFormatException {
		validateCodeService.create(request, response);
	}

	@GetMapping("oauth/test")
	public String testOauth() {
		return "oauth";
	}

	@GetMapping("user")
	public Principal  currentUser(Principal principal) {
		return principal;
	}

	@DeleteMapping("signout")
	public PSResponse signout(HttpServletRequest request) throws PSAuthException {
		String authorization = request.getHeader("Authorization");
		String token = StringUtils.replace(authorization, "bearer ", "");
		PSResponse psResponse = new PSResponse();
		if (!consumerTokenServices.revokeToken(token)) {
			throw new PSAuthException("退出登录失败");
		}
		return psResponse.message("退出登录成功");
	}

}
